package logic

import (
	"api/model/order_food_category"
	"api/service"
	"api/utils"
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"unicode/utf8"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderFoodCategoryAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderFoodCategoryAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderFoodCategoryAddLogic {
	return &OrderFoodCategoryAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderFoodCategoryAddLogic) OrderFoodCategoryAdd(req *types.RequestOrderFoodCategoryAdd) (resp *types.ResponseOrderFoodCategoryAdd, err error) {
	if utf8.RuneCountInString(req.Title) > 6 {
		return &types.ResponseOrderFoodCategoryAdd{
			Code: 200,
			Id:   0,
			Sort: 0,
		}, err
	}

	conn := sqlx.NewMysql(l.svcCtx.Config.DataSource)
	categoryModel := order_food_category.NewOrderFoodCategoryModel(conn)

	busService := service.NewBusinessService(l.ctx, l.svcCtx)
	bus := busService.GetLoginBusinessInfo()

	ret, err := categoryModel.Insert(l.ctx, &order_food_category.OrderFoodCategory{
		BusinessId: bus.Id,
		Title:      req.Title,
		CreateAt:   utils.GetCurDateTime(),
		Sort:       utils.GetCurTime(), // 默认当前时间
	})

	if err != nil {
		return &types.ResponseOrderFoodCategoryAdd{
			Code: 200,
			Id:   0,
			Sort: 0,
		}, err
	}

	id, _ := ret.LastInsertId()
	return &types.ResponseOrderFoodCategoryAdd{
		Code: 200,
		Id:   id,
		Sort: utils.GetCurTime(),
	}, err
}
